//
//  GroupFileCell.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/6/1.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "GroupFileCell.h"
#import "UIUtil.h"
#import "CFileModel.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "ChildHoodService.h"
#import "CXmppRequestMgr.h"
#import "CFolderMgr.h"
#import "Reachability.h"
#import "JKAlertDialog.h"
#import "MBProgressHUD+WZ.h"



#define KBLUECOLOR RGBCOLOR(0x2c, 0xaa, 0xfe)
#define KREDCOLOR RGBCOLOR(0xfb, 0x5d, 0x44)
#define KGREENCOLOR RGBCOLOR(0x14, 0xc6, 0x4a)
#define KGRAYCOLOR RGBCOLOR(0x92, 0x92, 0x92)

@implementation GroupFileCell

- (void)awakeFromNib
{
    // Initialization code
    _progress.layer.cornerRadius = 1.5f;
    _progress.transform = CGAffineTransformMakeScale(1.0f,3.0f);
    _progress.progressTintColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
    _progress.progress = 0.0f;
    _progress.layer.masksToBounds = YES;
    _progress.frame = CGRectMake(10, 87, 310, 3);
    _progress.trackTintColor = [UIColor lightGrayColor];
    [_progress setHidden:YES];
    
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    _seperatorLine.frame = CGRectMake(15, self.frame.size.height-0.5f, self.frame.size.width-15, 0.5f);

}

- (void)setFileModel:(CFileModel *)fileModel
{
    _fileModel = fileModel;
    
    CContactModel *model = [[[CContactMgr alloc] init] loadContactWithUserId:fileModel.fromUserId];
    self.fileIcon.image = [UIImage imageNamed:[UIUtil getFileIconByName:fileModel.FileName]];
    self.fileName.text = fileModel.FileName;
    CGSize fileNameSize = [UIUtil textSizeWithFont:[UIFont systemFontOfSize:16.0f] width:150.0f height:MAXFLOAT text:fileModel.FileName lineBreakMode:NSLineBreakByCharWrapping];
    self.fileName.frame = CGRectMake(77, 15, fileNameSize.width, 21);
    self.fileDownErr.frame = CGRectMake(CGRectGetMaxX(self.fileName.frame) + 5.0f, 19, 14, 14);
    self.fileSizenAndFrom.text = [NSString stringWithFormat:@"%.2fK  %@",fileModel.FileSize/1024.0,model.UserName];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:fileModel.CreateDate.longLongValue / 1000.0];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm EEEE"];
    NSString *targetDate = [formatter stringFromDate:date];
    
//直接显示时间 按照时间排序 YH
    self.fileTime.text = [targetDate substringToIndex:16];
    
    NSString *fileId = fileModel.GroupId;
//    if ([fileModel.fromUserId isEqualToString:[[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount].userId]) {
//        fileId = fileModel.fromUserId;
//    } else {
//        
//        fileId = fileModel.GroupId;
//    }
    
    NSString *filePath = [[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:fileId] stringByAppendingPathComponent:fileModel.serverFileName];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
//    self.fileTime.text = [UIUtil timeForMessageListStyle:date];
    
    if (data && data.length == fileModel.FileSize) {
        [_seperatorLine setHidden:NO];
        self.previewButton.hidden = NO;
        self.downButton.hidden = YES;
        self.fileDownErr.hidden = YES;
        self.fileDownOrPauseButton.hidden = YES;
        self.progress.hidden = YES;
    } else {
        self.previewButton.hidden = YES;
        
        
        __block NetAndAudioModel *netAndAudio = nil;
        [[CXmppRequestMgr shareInstance].operationArray enumerateObjectsUsingBlock:^(NetAndAudioModel *obj, NSUInteger idx, BOOL *stop) {
            if ([fileModel.serverFileName isEqualToString:obj.serFileName]) {
                netAndAudio = obj;
                *stop = YES;
            }
        }];
            if (netAndAudio) {
            [self setProgressValue:data.length / (float)fileModel.FileSize];
            self.downButton.hidden = YES;
            self.fileDownOrPauseButton.hidden = NO;
            self.progress.hidden = NO;
            self.seperatorLine.hidden = YES;
            self.fileDownErr.hidden = YES;

            if (netAndAudio.operation.isPaused) {
                self.fileDownOrPauseButton.selected = YES;
                _progress.progressTintColor = RGBCOLOR(246, 69, 53);
                [self.fileDownOrPauseButton setTitle:@"继续" forState:UIControlStateSelected];
                
            } else {
                
                self.fileDownOrPauseButton.selected = NO;
                _progress.progressTintColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
                
                [self.fileDownOrPauseButton setTitle:@"暂停" forState:UIControlStateNormal];
                
                NSData *data = [NSData dataWithContentsOfFile:filePath];
                NSMutableURLRequest *request = (NSMutableURLRequest *)netAndAudio.operation.request;
                [request setValue:[NSString stringWithFormat:@"bytes=%zd-%zd",data.length,self.fileModel.FileSize] forHTTPHeaderField:@"Range"];
                
                [netAndAudio.operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
                    NSData *data1 = [NSData dataWithContentsOfFile:filePath];
                    [self setProgressValue:data1.length / (float)self.fileModel.FileSize];
                }];
                
                __block NetAndAudioModel *netAudio = netAndAudio;
                

                [netAndAudio.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                    self.downButton.hidden = YES;
                    self.fileDownOrPauseButton.hidden = YES;
                    self.previewButton.hidden = NO;
                    self.fileDownErr.hidden = YES;
                    self.progress.hidden = YES;
                    [_seperatorLine setHidden:NO];
                    
                    [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    self.fileDownErr.hidden = NO;
                    fileModel.isFailure = YES;
                    self.downButton.hidden = NO;
                    [self.downButton setTitle:@"继续" forState:UIControlStateNormal];
                    self.fileDownOrPauseButton.hidden = YES;
                    self.previewButton.hidden = YES;
                    self.progress.hidden = NO;
                    [_seperatorLine setHidden:YES];
                    [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
                }];
            }

                
            } else {
                if (data.length == 0) {
                    [self.downButton setTitle:@"下载" forState:UIControlStateNormal];
                    self.downButton.hidden = NO;
                    self.fileDownErr.hidden = YES;
                    self.progress.hidden = YES;
                    self.seperatorLine.hidden = NO;
                    self.fileDownOrPauseButton.hidden = YES;
                } else {
                    self.fileDownErr.hidden = NO;
                    [self setProgressValue:data.length / (float)fileModel.FileSize];
                    self.progress.hidden = NO;
                    self.seperatorLine.hidden = YES;
                    [self.downButton setTitle:@"继续" forState:UIControlStateNormal];
                     self.downButton.hidden = NO;
                    self.fileDownOrPauseButton.hidden = YES;
                }

            }
            
        
    }
    
    
    
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

   
}

- (void)downFile:(UIButton *)sender
{
//    if ([self checkNetWork]) {
        self.downButton.hidden = YES;
        self.fileDownOrPauseButton.hidden = NO;
        self.fileDownErr.hidden = YES;
        _progress.progressTintColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
        NSString *fileId = self.fileModel.GroupId;
       __block  NSString *filePath = [[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:fileId] stringByAppendingPathComponent:self.fileModel.serverFileName];
//        if ([self.fileModel.fromUserId isEqualToString:[[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount].userId]) {
//            fileId = self.fileModel.fromUserId;
//        } else {
//            fileId = self.fileModel.GroupId;
//            
//        }
    
    self.progress.hidden = NO;
    _seperatorLine.hidden = YES;
//    NSData *data1 = [NSData dataWithContentsOfFile:[[[ChildHoodService defaultService] filePathWithUserId:fileId] stringByAppendingPathComponent:self.fileModel.FileName]];
//    [self setProgressValue:data1.length / (float)self.fileModel.FileSize];
    
        __block NetAndAudioModel *netAndAudio = nil;
        [[CXmppRequestMgr shareInstance].operationArray enumerateObjectsUsingBlock:^(NetAndAudioModel *obj, NSUInteger idx, BOOL *stop) {
            if ([self.fileModel.serverFileName isEqualToString:obj.serFileName]) {
                netAndAudio = obj;
                *stop = YES;
            }
        }];
        if (netAndAudio) {
            NSData *data = [NSData dataWithContentsOfFile:filePath];
            NSMutableURLRequest *request = (NSMutableURLRequest *)netAndAudio.operation.request;
            [request setValue:[NSString stringWithFormat:@"bytes=%zd-%zd",data.length,self.fileModel.FileSize] forHTTPHeaderField:@"Range"];

            [netAndAudio.operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    
                NSData *data1 = [NSData dataWithContentsOfFile:filePath];
                [self setProgressValue:data1.length / (float)self.fileModel.FileSize];
            }];
            
            __block NetAndAudioModel *netAudio = netAndAudio;
            [netAndAudio.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                self.downButton.hidden = YES;
                self.fileDownOrPauseButton.hidden = YES;
                self.previewButton.hidden = NO;
                self.fileDownErr.hidden = YES;
                self.progress.hidden = YES;
                [_seperatorLine setHidden:NO];
                [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                self.fileDownErr.hidden = NO;
                self.fileModel.isFailure = YES;
                self.downButton.hidden = NO;
                [self.downButton setTitle:@"继续" forState:UIControlStateNormal];
                self.fileDownOrPauseButton.hidden = YES;
                self.previewButton.hidden = YES;
                self.progress.hidden = NO;
                [_seperatorLine setHidden:YES];
                [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            }];
            return;
        }
        

        [[CXmppRequestMgr shareInstance] downLoadeGroupWithFileNmae:self.fileModel.serverFileName GroupId:self.fileModel.GroupId dataType:@"file" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            self.downButton.hidden = YES;
            self.fileDownOrPauseButton.hidden = YES;
            self.previewButton.hidden = NO;
            self.fileDownErr.hidden = YES;
            self.progress.hidden = YES;
            [_seperatorLine setHidden:NO];
        } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
            self.fileDownErr.hidden = NO;
            self.downButton.hidden = NO;
            [self.downButton setTitle:@"继续" forState:UIControlStateNormal];
            self.fileDownOrPauseButton.hidden = YES;
            self.previewButton.hidden = YES;
            self.progress.hidden = NO;
            self.fileModel.isFailure = YES;
            [_seperatorLine setHidden:YES];
            
        } progressHandle:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            
            NSData *data1 = [NSData dataWithContentsOfFile:filePath];
            self.progressValue = data1.length / (float)self.fileModel.FileSize;
           
            
        } dataLenth:[NSString stringWithFormat:@"%zd",self.fileModel.FileSize] filePath:filePath];
//    }
   }

- (void)updateProgress
{
    NSString *filePath = [[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:self.fileModel.GroupId] stringByAppendingPathComponent:self.fileModel.serverFileName];
    NSData *data1 = [NSData dataWithContentsOfFile:filePath];
    [self setProgressValue:data1.length / (float)self.fileModel.FileSize];

}
- (IBAction)PauseCheckNetWorkWithNetAudio:(NetAndAudioModel *)netAndAudio
{
    
    
    Reachability *r = [[CXmppMgr shareInstance] reachability];
    if ([r currentReachabilityStatus]==0) {
        // 没有网络连接
//        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"网络不可用!"];
//        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            [MBProgressHUD showError:@"网络不可用!"];
            self.fileDownErr.hidden = NO;
            self.fileModel.isFailure = YES;
            self.downButton.hidden = NO;
            [self.downButton setTitle:@"继续" forState:UIControlStateNormal];
            self.fileDownOrPauseButton.hidden = YES;
            self.previewButton.hidden = YES;
            self.progress.hidden = NO;
            [_seperatorLine setHidden:YES];
            
//        }];
//        [alert show];
    
        
    }else if([r currentReachabilityStatus]==1){
        // 使用3G网络
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:[NSString stringWithFormat:@"当前为非WiFi网络，是否恢复下载%@ (%.2fK)",self.fileModel.FileName,self.fileModel.FileSize / 1024.0]];
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            
            _progress.progressTintColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
            self.fileDownOrPauseButton.selected = NO;
            [self.fileDownOrPauseButton setTitle:@"暂停" forState:UIControlStateNormal];
            
             [netAndAudio.operation resume];
            
             }];
        
        
        [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
            self.fileDownOrPauseButton.selected = YES;
            [self.fileDownOrPauseButton setTitle:@"继续" forState:UIControlStateNormal];
        }];
        [alert show];
        
    }else if([r currentReachabilityStatus]==2){
        //        wifi
        
        _progress.progressTintColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
        
        self.fileDownOrPauseButton.selected = NO;
        [self.fileDownOrPauseButton setTitle:@"暂停" forState:UIControlStateNormal];
       
        
        [netAndAudio.operation resume];
    }
}



- (IBAction)checkNetWork{
    
    Reachability *r = [[CXmppMgr shareInstance] reachability];
    if ([r currentReachabilityStatus]==0) {
        // 没有网络连接
        [MBProgressHUD showError:@"网络不可用!"];
        
    }else if([r currentReachabilityStatus]==1){
        // 使用3G网络
        NSString *tile = nil;
        if ([self.downButton.currentTitle isEqualToString:@"继续"]) {
         tile = @"当前为非WiFi网络环境，是否恢复下载";
        } else {
            tile = @"当前为非WiFi网络环境，确定下载";
        }
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"%@%@ (%.2fK)",tile,self.fileModel.FileName,self.fileModel.FileSize / 1024.0] preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *alertYES = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [self downFile:nil];
//        }];
//        UIAlertAction *alertNO = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            
//        }];
//        [alert addAction:alertYES];
//        [alert addAction:alertNO];
        JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:[NSString stringWithFormat:@"%@%@ (%.2fK)",tile,self.fileModel.FileName,self.fileModel.FileSize / 1024.0]];
        [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
            [self downFile:nil];
        }];
        
        [alert addButton:Button_CANCEL withTitle:@"取消" handler:^(JKAlertDialogItem *item) {
            
        }];
        [alert show];
        
    }
        else if([r currentReachabilityStatus]==2){
        //        wifi
        [self downFile:nil];
        
    }
}


- (IBAction)fileDownOrPauseButton:(UIButton *)button
{
    
    button.selected = !button.selected;
    NSString *fileId = self.fileModel.GroupId;
//    if ([self.fileModel.fromUserId isEqualToString:[[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount].userId]) {
//        fileId = self.fileModel.fromUserId;
//    } else {
//        fileId = self.fileModel.GroupId;
//        
//    }

       __block NetAndAudioModel *netAndAudio = nil;
    [[CXmppRequestMgr shareInstance].operationArray enumerateObjectsUsingBlock:^(NetAndAudioModel *obj, NSUInteger idx, BOOL *stop) {
        if ([self.fileModel.serverFileName isEqualToString:obj.serFileName]) {
            netAndAudio = obj;
            *stop = YES;
        }
    }];

        if (netAndAudio) {
            NSData *data = [NSData dataWithContentsOfFile:[[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:fileId] stringByAppendingPathComponent:self.fileModel.serverFileName]];
            NSMutableURLRequest *request = (NSMutableURLRequest *)netAndAudio.operation.request;
            [request setValue:[NSString stringWithFormat:@"bytes=%zd-%zd",data.length,self.fileModel.FileSize] forHTTPHeaderField:@"Range"];
            [netAndAudio.operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
            NSData *data1 = [NSData dataWithContentsOfFile:[[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:fileId] stringByAppendingPathComponent:self.fileModel.serverFileName]];
            [self setProgressValue:data1.length / (float)self.fileModel.FileSize];
            }];
            
            __block NetAndAudioModel *netAudio = netAndAudio;
            [netAndAudio.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                self.downButton.hidden = YES;
                self.fileDownOrPauseButton.hidden = YES;
                self.previewButton.hidden = NO;
                self.fileDownErr.hidden = YES;
                self.progress.hidden = YES;
                [_seperatorLine setHidden:NO];
                
                [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                self.fileDownErr.hidden = NO;
                self.fileModel.isFailure = YES;
                self.downButton.hidden = NO;
                [self.downButton setTitle:@"继续" forState:UIControlStateNormal];
                self.fileDownOrPauseButton.hidden = YES;
                self.previewButton.hidden = YES;
                self.progress.hidden = NO;
                [_seperatorLine setHidden:YES];
                
                [[CXmppRequestMgr shareInstance].operationArray removeObject:netAudio];
            }];
            
        if (button.selected) {
            
            _progress.progressTintColor = RGBCOLOR(246, 69, 53);
            [button setTitle:@"继续" forState:UIControlStateSelected];
            //        [button setBackgroundColor: RGBCOLOR(0x2c, 0xaa, 0xfe)];
            [netAndAudio.operation pause];
        } else {
            button.selected = NO;
            [self PauseCheckNetWorkWithNetAudio:netAndAudio];
            
        }
    }

}

- (IBAction)openfileButton:(UIButton *)sender
{
    if ([self.groupFileCellDelegate respondsToSelector:@selector(GroupFileCellDidOpenFileWithIndexPath:)]) {
        [self.groupFileCellDelegate GroupFileCellDidOpenFileWithIndexPath:self.indexPath];
    }
}
-(void)setProgressValue:(CGFloat)progressValue
{
    _progressValue = progressValue;
//    if (progressValue > 0) {
        [_progress setProgress:progressValue animated:NO];

//    } else {
//        [_progress setHidden:YES];
//        [_seperatorLine setHidden:NO];
 
}

@end
